<template>
  <div class="com-page">
    <div ref="container" class="com-container" />
  </div>
</template>

<script>
import { setEcharts, setEchartOptions } from '@/api/echarts/rank.js'
export default {
  data() {
    return {
      seriesData: '',
      xAxisData: '',
      start: 0,
      end: 9,
      timer: null
    }
  },
  async mounted() {
    await this.initCharts()
    this.setEcharts()
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.timer = setInterval(() => {
      if (this.end === this.seriesData.length - 1) {
        this.start = -1
        this.end = 8
      }
      this.start++
      this.end++
      this.setEcharts()
    }, 3000)
    window.addEventListener('resize', this.screenAdapter)
  },
  methods: {
    // 获取echarts的数据
    async initCharts() {
      const { data } = await this.$http.get('/rank')
      console.log(data)
      this.seriesData = data.map((item) => item.value)
      this.seriesData = this.seriesData.sort((a, b) => {
        return b - a
      })
      this.xAxisData = data.map((item) => item.name)
    },
    // 渲染echarts图表 柱形图
    setEcharts() {
      setEcharts(
        this.$refs.container,
        this.xAxisData,
        this.seriesData,
        this.start,
        this.end
      )
    },
    // 屏幕分辨率 改变时 option 变化
    screenAdapter() {
      const titleFontSize = (this.$refs.container.offsetWidth / 100) * 3.6
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        series: {
          barWidth: titleFontSize,
          itemStyle: {
            barBorderRadius: [0, titleFontSize / 2, titleFontSize / 2, 0]
          }
        }
      }
      setEchartOptions(this.$refs.container, adapterOption)
    }
  }
}
</script>

<style lang="scss" scoped></style>
